package com.ck.queue;

import java.util.LinkedList;
import java.util.Queue;

public class TestMain {

    private Object lock = new Object();

    private Queue<Object> list = new LinkedList<>();

    private final static int maxLenth = 10;

    private Integer i = 0;

    private void add(){
        while (true){
            synchronized (lock) {
                if(list.size() == maxLenth) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        System.out.println("list size:" + list.size());
                        lock.notifyAll();
                    }
                } else {
                    list.add("data:" + ++i);
                    System.out.println("add obj value:" + "data:" +i + "list size:"+list.size());
                    lock.notifyAll();
                    break;
                }
            }
        }
    }

    /**
     * 获取元素
     *
     * @return
     */
    public Object get() {

        while (true) {
            synchronized (lock) {
                if (list.size() <= 0) {
                    //  System.out.println("没有元素请等待");
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        System.out.println("队列空了当前list长度：" + list.size());
                        lock.notifyAll();
                    }
                } else {

                    Object poll = list.poll();
                    System.out.println("移除obj值: " + poll +" 当前list长度：" + list.size());
                    lock.notifyAll();
                    return poll;
                }
            }
        }

    }

    public static void main(String[] args) {
        final TestMain tm = new TestMain();


        // 启动5个添加数据线程

        for (int i = 0; i < 20; i++) {
            new Thread(() -> tm.add()).start();

        }

        // 启动5个获取数据线程
        for (int i = 0; i < 20; i++) {
            new Thread(() -> tm.get()).start();

        }

    }

}
